package com.higgins.client.agentapp.components;

import java.util.List;
import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ListBox;
import com.higgins.client.agentapp.datamodel.AgencyDTO;
import com.higgins.client.agentapp.datamodel.AgentDTO;
import com.higgins.client.agentapp.interfaces.AgencyListChangeHandler;
import com.higgins.client.agentapp.interfaces.AgencyListListener;
import com.higgins.client.agentapp.interfaces.AgentListChangeHandler;
import com.higgins.client.agentapp.interfaces.AgentListListener;
import com.higgins.client.agentapp.service.AgentAppService;
import com.higgins.client.agentapp.service.AgentAppServiceAsync;

public class AgentListBox extends ListBox implements ChangeHandler	{
	private static final Logger log = Logger.getLogger(AgentListBox.class.getName());
	private final AgentAppServiceAsync agentAppService = GWT
			.create(AgentAppService.class);
	private Long agencyId = null;
	private List<AgentDTO> agentList = null;
	private AgentListChangeHandler changeHandler = null;
	
	public AgentListBox()	{
		super();
	}
	public void setAgencyId(Long agencyId)	{
		this.agencyId = agencyId;
		requestData();
	}
	public void addAgentListChangeHandler(AgentListChangeHandler changeHandler)	{
		this.changeHandler = changeHandler;
		this.addChangeHandler(this);
	}
	
	private void requestData()	{
		try {
			agentAppService.retrieveAgents(agencyId, new AsyncCallback<List<AgentDTO>>()	{
					@Override
					public void onFailure(Throwable caught) {
						log.info("StrategyColumns: " + caught.toString());
					}

					@Override
					public void onSuccess(List<AgentDTO> result) {
//						List<String> list = new ArrayList<String>();
//						for (CoveringLetterDTO coveringLetterDTO:result)	{
//							list.add(coveringLetterDTO.getName());
//						}
						applyResultsToListBox(result);
					}
				});
		} catch (IllegalArgumentException e) {
			log.info("StrategyColumns: " + e.toString());
		}			
	}

	private void applyResultsToListBox(List<AgentDTO> agentDTOs)	{
		agentList = agentDTOs;
		this.clear();
		this.addItem("");
		for (AgentDTO agentDTO:agentDTOs)	{
			this.addItem(agentDTO.getName());
		}
	}
	@Override
	public void onChange(ChangeEvent event) {
		changeHandler.onAgentListChange(event);
	}
	public Long getAgentId()	{
		Integer selected = this.getSelectedIndex();
		if (selected <= 0 || agentList==null)
			return null;
		AgentDTO dto = agentList.get(selected-1);
		return dto.getId();
	}
}
